﻿myApp.controller("homeLoanCalculatorController", function ($scope, modalService) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 HomeLoan Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 HomeLoan Calculator', 'description': 'Free online home loan calculator. Try it now.' });
    $scope.purchasePrice = 600000;
    $scope.marginFinance = 90;
    $scope.loanAmount = $scope.purchasePrice * $scope.marginFinance / 100;
    $scope.interestRate = 5;
    $scope.tenure = 30;
    $scope.mrta = 0;
    $scope.others = 0;
    $scope.total = $scope.loanAmount + $scope.mrta + $scope.others;

   $scope.calculate =  function ()
    {

        var purchase_price = $scope.purchasePrice;
        var margin_finance = $scope.marginFinance;
        var loan_amount = purchase_price * margin_finance / 100;
        $scope.total= $scope.loanAmount + $scope.mrta + $scope.others;
        var total_loan_amount = $scope.total;       
        $scope.total_months = $scope.tenure * 12;
        var r = $scope.interestRate / (12 * 100);
        var p = (total_loan_amount * r * Math.pow((1 + r), $scope.total_months)) / (Math.pow((1 + r), $scope.total_months) - 1);
        var prin = Math.round(p * 100) / 100;
        $scope.monthlyPayment = prin;      
        var mon = Math.round((($scope.total_months * prin) - total_loan_amount) * 100) / 100;
        $scope.totalInterest = mon;
        var tot = Math.round((mon / $scope.total_months) * 100) / 100;
        $scope.monthlyInterest = tot;
        $scope.totalPayment = Math.round(prin * $scope.total_months);

      
    }
    $scope.generateTable = function () {
        $scope.calculate();
        $scope.calc = true;
        //var total_months = $("#txtTenure").val() * 12;
        //var total_payment = $("#txtTotalPayment").val();
        //var monthly_payment = $("#txtMonthlyPayment").val();
        //var monthly_interest = $("#txtMonthlyIntest").val();
        //var total_loan_amount = $("#txtTotal").val();
        var monthly_principle = $scope.monthlyPayment - $scope.monthlyInterest;
        var loan_balance = $scope.totalPayment;
        var monthly_principle_balance = $scope.total;

        $scope.payments = [];
     
        for (var i = 1; i <= $scope.total_months; i++) {
            loan_balance = loan_balance - $scope.monthlyPayment;
            monthly_principle_balance = monthly_principle_balance - monthly_principle;
            $scope.payments[i] = { month: i, loan_balance: loan_balance, monthly_principle_balance: monthly_principle_balance, monthly_interest: $scope.monthlyInterest };
            
        }
      

    }

    function pageInit()
    {
        $scope.calculate();
    }
    pageInit();

})
myApp.controller("listEntryController", function ($scope, $http, $modal, modalService, $routeParams, $location, $window,$sce) {
    $scope.form = {};
    $scope.uploadedImages = [];
    $scope.locationDropdown = {};
    $scope.stateDropdown = {};
    $scope.property = {};
    $scope.isopen = true;
    $scope.propertyUrl = $sce.trustAsResourceUrl('http://lskweb.dlinkddns.com/propertyentryweb.aspx');
    //$scope.propertyUrl = $sce.trustAsResourceUrl('http://localhost/REM/propertyentryweb.aspx');
    //var eventMethod = window.addEventListener ? "addEventListener" : "attachEvent";
    //var eventer = window[eventMethod];
    //var messageEvent = eventMethod == "attachEvent" ? "onmessage" : "message";

    //// Listen to message from child window
    //eventer(messageEvent, function (e) {
    // //   console.log('parent received message!:  ', e.data);
    //}, false);

    
    function pageInit() {
        $scope.loader.loading = true;
        console.log($scope.property);

        // TODO : Getting the authentication user objec, I already get it at the page controller and save in local storage
        // another way to get the data is : authService.authentication, refer PageController, inject the service
        console.log("User Info");
        console.log($scope.authentication);
        if ($scope.authentication.isAuth === false) $location.path('/Login');
        if ($scope.authentication.userType == "Valid User") $location.path('/#');
        if ($scope.authentication.userName.indexOf('@') !== -1)
        {
            console.log("@ found");
            $location.path('/#');
        }


        $http.get('api/Property/GetState')
        .success(function (data) {
            $scope.states = data;
        }
        )

        $http.get('api/Property/GetPropertyType')
           .success(function (data) {
               $scope.propertyTypes = data;
           }
           )

        if ($routeParams.id) {
           
            
            var url = 'api/Property/GetProperty/' + $routeParams.id;
            $http.get(url).success(function (data) {
                $scope.property = data.property;
                $scope.stateDropdown = data.stateList;
                $scope.locations = data.locationList;
                $scope.roadNames = data.roadList;
                $scope.projects = data.projectList;
                $scope.states = data.stateList;
                $scope.property.ListType = $scope.property.ListType ? $scope.property.ListType.toString() : "";
                $scope.propertyUrl = $sce.trustAsResourceUrl('http://lskweb.dlinkddns.com/propertyentryweb.aspx?id=' + $routeParams.id + '&userId=' + $scope.authentication.userType + '&ListType=' + $scope.property.ListType);
              //  $scope.propertyUrl = $sce.trustAsResourceUrl('http://localhost/REM/propertyentryweb.aspx?id=' + $routeParams.id + '&userId=' + $scope.authentication.userType + '&ListType=' + $scope.property.ListType);
                if (data.pictureList)
                {
                    angular.forEach(data.pictureList, function (object) {
                        $scope.uploadedImages.push({ uploadedImgSrc: object.pictureURL, PhotoId: object.PictureDesc });
                    })
                }
                $scope.loader.loading = false;
               
            })
        }
        $scope.loader.loading = false;


    }


    $scope.single = function (image) {
        $scope.loader.loading = true;
        var formData = new FormData();
        console.log(image);
        //formData.append('image', image.file);
        formData.append('image', image.dataURL);
        formData.append('property', angular.toJson($scope.property));
        $http.post('api/Property/upload', formData, {
            headers: { 'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function (result) {
            $scope.clear();
            $scope.uploadedImages.push({ uploadedImgSrc: result.OriginalUrl, PhotoId: result.PhotoId });
            $scope.loader.loading = false;

        });
    }

    $scope.changeState = function () {
        if ($scope.property.StateId) {
            $http.get('api/Property/GetLocation/' + $scope.property.StateId)
           .success(function (data) {

               $scope.locations = data;
           }
           )
        }
    }

    $scope.changeLocation = function () {
        if ($scope.property.LocationId) {
            $http.get('api/Property/GetRoadName/' + $scope.property.LocationId)
           .success(function (data) {
               $scope.roadNames = data;
           }
           )
        }
    }

    $scope.changeRoadName = function () {
        if ($scope.property.RoadId) {
            $http.get('api/Property/GetProject/' + $scope.property.RoadId)
           .success(function (data) {
               $scope.projects = data;
           }
           )
        }
    }
    
    $scope.close = function () {

        $scope.warning = null;
        $scope.error = null;
        $scope.info = null;
    }

    $scope.clear = function (image) {
        angular.element("input[type='file']").val(null);
        imaage = null;
        $scope.image = null;
        $scope.data.image = null;
        $scope.form.uploadPhoto.$setPristine();
       
      //  $scope.$apply();
    }

    $scope.deleteImage = function (image) {

        $scope.loader.loading = true;
        $http.post('api/Property/DeletePhoto', image.PhotoId)
        .success(function (result) {
            var index = $scope.uploadedImages.map(function (e) { return e.PhotoId; }).indexOf(image.PhotoId)
            $scope.uploadedImages.splice(index, 1);
            $scope.loader.loading = false;
        })
        console.log(image);
    }

    function validation()
    {
        $scope.warning = [];

        if (!$scope.property.RoadId)
            $scope.warning.push({ msg: "Road must not be empty!" });
        if (!$scope.property.StateId)
            $scope.warning.push({ msg: "State must not be empty!" });
        if (!$scope.property.ProjectId)
            $scope.warning.push({ msg: "Project must not be empty!" });
        if (!$scope.property.ListType)
            $scope.warning.push({ msg: "List Type must not be empty!" });
        if (!$scope.property.LocationId)
            $scope.warning.push({ msg: "Location must not be empty!" });
        if (!$scope.property.PropertyTypeId)
            $scope.warning.push({ msg: "Property Type must not be empty!" });
        if (!$scope.property.UnitNumber)
            $scope.warning.push({ msg: "Unit Number must not be empty!" });
        //if ($scope.property.UnitNumber && isNaN($scope.property.UnitNumber))
        //    $scope.warning.push({ msg: "Unit Number must not be empty!" });
        if (!$scope.property.BUWidth)
            $scope.warning.push({ msg: "BUWidth must be an integer!" });
        if (!$scope.property.BULength)
            $scope.warning.push({ msg: "BULength must be an integer!" });
        if (!$scope.property.SRYes && !$scope.property.SCYes && !$scope.property.SLYes
            && !$scope.property.SIYes && ($scope.property.ListType == 1 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Sale and make sure the price is greter than 0" });
        if (!$scope.property.RRYes && !$scope.property.RCYes && !$scope.property.RLYes
            && !$scope.property.RRYes && ($scope.property.ListType == 2 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Rent and make sure the price is greter than 0" });
        if (!$scope.property.SRAmt && !$scope.property.SCAmt && !$scope.property.SLAmt
            && !$scope.property.SIAmt && ($scope.property.ListType == 1 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Sale and make sure the price is greter than 0" });
        if (!$scope.property.RRAmt && !$scope.property.RCAmt && !$scope.property.RLAmt
            && !$scope.property.RIAmt && ($scope.property.ListType == 2 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Rent and make sure the price is greter than 0" });
        if ($scope.property.SRAmt<=0 && $scope.property.SCAmt <=0 && $scope.property.SLAmt <= 0
            && $scope.property.SIAmt <=0 && ($scope.property.ListType == 1 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Sale and make sure the price is greter than 0" });
        if ($scope.property.RRAmt<=0 && $scope.property.RCAmt<=0 && $scope.property.RLAmt <= 0
            && $scope.property.RIAmt <=0 && ($scope.property.ListType == 2 || $scope.property.ListType == 3))
            $scope.warning.push({ msg: "Choose at least one Rent and make sure the price is greter than 0" });
        if ($scope.warning.length > 0)
            return false;
        else {
            // Insert the slister and rlisterid
            if ($scope.property.ListType == 1 || $scope.property.ListType == 3) $scope.property.SListerId = $scope.authentication.userType;
            if ($scope.property.ListType == 2 || $scope.property.ListType == 3) $scope.property.SListerId = $scope.authentication.userType;
            $scope.warning = null;
            return true;
        }
    }

    $scope.clearEntry = function()
    {
        $location.path("/ListingEntry/");
    }

    $scope.save = function () {
        if (!validation()) {
            window.scrollBy(0, -10000);
            return;
        }
        
        $scope.property.BUSF = $scope.property.BUWidth * $scope.property.BULength;
        
        $http.post('api/Property/save', $scope.property)
            .success(function (result) {
                $scope.property.PropertyId = result.Message;
                $scope.property = result.property;
                $scope.property.ListType = $scope.property.ListType.toString();

                $scope.info = "Save successful";
                // if is first time created, reload
                if (!$location.path().split("/")[2])
                    $location.path("/ListingEntry/"  + $scope.property.PropertyId);
            })
    }

    $scope.close = function () {
        $scope.warning = null;
        $scope.info = null;
        $scope.error = null;
    }

    pageInit();
});
myApp.controller("loginController", function ($scope, $http, $modal, $routeParams, authService, $location, $window, $rootScope) {
    $scope.loader.loading = false;
    $scope.login = function () {
        if (!$scope.loginData || !$scope.loginData.userName || !$scope.loginData.password) {
            $scope.message = "Invalid username or password!";
            return;
        }
        authService.login($scope.loginData).then(function (response) {
            $scope.user = $scope.loginData;
            
            if ($scope.authentication.userType == "Valid User") $location.path('/#');
            if ($scope.authentication.userName.indexOf('@') === -1) {
                $location.path('/ListingEntry');
            } else { $location.path('/News'); }
            

        },
         function (err) {
             $scope.message = "Invalid username or password!";
         });
    };

})
myApp.controller("newsDetailController", function ($scope, $http, $modal, modalService, $routeParams, $location) {
    $scope.share = {};
    console.log('News Details');
    function pageInit() {
        var url = 'api/News/GetNew/' + $routeParams.id;
        $http.get(url).success(function (data) {
            $scope.News = data.MobileNews;
            $scope.News.CreateDate = new Date($scope.News.CreateDate);
            $scope.slides = data.pictureList;


            $scope.share.url = 'http://www.penangrealty.my/NewDetail/' + $routeParams.id.toString();
            $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
            $scope.share.description = "[" + $scope.News.Title + '] ' + $scope.News.Source + " - " + $scope.News.CreateDate
    + '\n' + $scope.News.Details + '\n' + window.location.href + '\n';
            //+ "Contact: " + $scope.property.mobile + " (" + $scope.property.agentname + ")";
            document.title = "Penang Realty 世界地產 " + $scope.News.Title;
            $scope.$emit('newPageLoaded', { 'title': $scope.News.Title, 'description': $scope.News.Details });
        })
       
    }

    pageInit();
});
myApp.controller("newsController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {
    document.title = "Penang Realty 世界地產 News";

    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 News', 'description': 'First hand property news. Updated instantly.' });
    $scope.thisPage = {};
    function pageInit() {
        $scope.thisPage.loading = true;
        var url = 'api/News/GetNews';
        $http.get(url).success(function (data) {
            $scope.thisPage.loading = false;
            $scope.data.News = data;


            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 25,           // count per page
                filter: {
                    Title: ''       // initial filter
                }
            
            }, {
                total: $scope.data.News.length, // length of data
                getData: function ($defer, params) {

                    var orderedNews = params.filter() ?  $filter('filter')($scope.data.News, params.filter()) :  $scope.data.News;
                    // use build-in angular filter
                    orderedNews = params.sorting() ?
                            $filter('orderBy')(orderedNews, params.orderBy()) : orderedNews;

                    params.total(orderedNews.length); // set total for recalc pagination
                    $defer.resolve(orderedNews.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    $scope.loader = { loading: false };
                }
            })


        })
        
    }


    pageInit();


})
myApp.controller("pageController", function ($scope, $http, $modal, modalService, $sce, $timeout, authService, $location,$rootScope) {
    $rootScope.waypointInit = $rootScope.waypointInit || false;
    $scope.data = {};
    $scope.isHome = false;

    var offset = $("#menu_bar").outerHeight() + 1;

    

    $('.menu_bar-waypoint').each(function (i) {
        var $el = $(this),
            animClassDown = $el.data('animateDown'),
            animClassUp = $el.data('animateUp');

        //console.log($el);
        $el.waypoint(function (direction) {
            var $head = $('#menu_bar');
            if (!$scope.isHome) {

            }
            else if (direction === 'down' && animClassDown) {
                $head.attr('class', 'menu_bar ' + animClassDown);
            }
            else if (direction === 'up' && animClassUp) {
                $head.attr('class', 'menu_bar ' + animClassUp);
            }
        }, {
            offset: function () {
                return offset;
            }
        });
    });
    $rootScope.$on('NavHomePage', function (event, data) {
        var $head = $('#menu_bar');
        $scope.isHome = true;
        $head.attr('class', 'menu_bar ' + 'menu_bar-hide');
        $.scrollTo('.hero_fullscreen', 1000, { easing: 'easeInOutExpo', 'axis': 'y' });
        console.log("Back Home Page");
        initWayPoint();
        resetWayPoint();
    });
    $rootScope.$on('NavOtherPage', function (event, data) {
        var $head = $('#menu_bar');
        $scope.isHome = false;
        $head.attr('class', 'menu_bar ' + 'menu_bar-show');
        $.scrollTo('.hero_fullscreen', 1000, { easing: 'easeInOutExpo', 'axis': 'y' });
        console.log("Navigate to Other Page");
    });

    function initWayPoint() {
        if (!$rootScope.waypointInit) {
            setTimeout(function () {
                $('#more_info').waypoint(function () {
                    setTimeout(function () { $('.content_anim1').addClass('animated fadeInUp') }, 0);
                    setTimeout(function () { $('.content_anim2').addClass('animated fadeInUp') }, 200);
                    setTimeout(function () { $('.content_anim3').addClass('animated fadeInUp') }, 400);
                    setTimeout(function () { $('.content_anim4').addClass('animated fadeInUp') }, 600);
                    setTimeout(function () { $('.content_anim5').addClass('animated fadeInUp') }, 800);
                }, { offset: '50%' });

                $('#contact').waypoint(function () {
                    setTimeout(function () { $('.content_anim29').addClass('animated fadeInUp') }, 0);
                    setTimeout(function () { $('.content_anim30').addClass('animated fadeInUp') }, 200);
                }, { offset: '50%' });
                $rootScope.waypointInit = true;
            }, 300);
        }
    }
    function resetWayPoint() {
        $('.content_anim29').removeClass('animated fadeInUp');
        $('.content_anim30').removeClass('animated fadeInUp');
    }

   function pageInit() {
        $scope.loader = { loading: true };
        var url = 'api/Page/GetSetting';
        $http.get(url).success(function (data) {
           $scope.data.setting =data;
           $scope.loader = { loading: false };
        })

        $rootScope.authentication = authService.authentication;

    }
    $scope.disclaimer = function () {

        //$scope.animationsEnabled = true;
        //var modalInstance = $modal.open({
        //    animation: $scope.animationsEnabled,
        //    templateUrl: 'view/Disclaimer.html',
        //    //controller: 'ModalInstanceCtrl',
        //    size: 'lg',


        //})

        var modalOptions = {
            closeButtonText: 'Cancel',
            actionButtonText: 'Ok',
            headerText: 'Disclaimer',
            bodyText: $sce.trustAsHtml($scope.data.setting.Disclaimer)
        };

        modalService.showModal({}, modalOptions);
    }
    $scope.getUsername = function () {
        if (authService) {
            if (authService.authentication) {
                if (authService.authentication.isAuth) {
                    if (authService.authentication.userName) {
                        if (authService.authentication.userName.length > 15) {
                            return authService.authentication.userName.substring(0, 15) + "...";
                        }
                        return authService.authentication.userName;
                    }
                }
            }
        }
        return "";
    }
    $scope.logout =function()
    {
        authService.logOut();
        $location.path('/Home');
    }

    pageInit();

});
myApp.controller("rpgtController", function ($scope, $http, $modal, $routeParams, authService, $location, $window) {
    document.title = "Penang Realty 世界地產 RPGT Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 RPGT Calculator', 'description': 'Free online RPGT calculator. Try it now.' });

    //$scope.today = function () {
    //    $scope.dt = new Date();
    //};
    //$scope.today();

    //$scope.clear = function () {
    //    $scope.dt = null;
    //};

    //// Disable weekend selection
    //$scope.disabled = function (date, mode) {
    //    return (mode === 'day' && (date.getDay() === 0 || date.getDay() === 6));
    //};

    //$scope.toggleMin = function () {
    //    $scope.minDate = $scope.minDate ? null : new Date();
    //};
    //$scope.toggleMin();

    //$scope.open = function ($event) {
      
    //    $scope.opened = true;
    //    $event.preventDefault();
    //    $event.stopPropagation();
    //};

    //$scope.dateOptions = {
    //    formatYear: 'yy',
    //    startingDay: 1
    //};

    //$scope.formats = ['dd-MMMM-yyyy', 'yyyy/MM/dd', 'dd.MM.yyyy', 'shortDate'];
    //$scope.format = $scope.formats[0];

    //$scope.status = {
    //    opened: false
    //};

    //var tomorrow = new Date();
    //tomorrow.setDate(tomorrow.getDate() + 1);
    //var afterTomorrow = new Date();
    //afterTomorrow.setDate(tomorrow.getDate() + 2);
    //$scope.events =
    //  [
    //    {
    //        date: tomorrow,
    //        status: 'full'
    //    },
    //    {
    //        date: afterTomorrow,
    //        status: 'partially'
    //    }
    //  ];

    //$scope.getDayClass = function (date, mode) {
    //    if (mode === 'day') {
    //        var dayToCheck = new Date(date).setHours(0, 0, 0, 0);

    //        for (var i = 0; i < $scope.events.length; i++) {
    //            var currentDay = new Date($scope.events[i].date).setHours(0, 0, 0, 0);

    //            if (dayToCheck === currentDay) {
    //                return $scope.events[i].status;
    //            }
    //        }
    //    }

    //    return '';
    //};


    $scope.totalExpenses = function () {

        $scope.totalExpensesFee = ($scope.other ? $scope.other : 0) + ($scope.repairFee ? $scope.repairFee : 0) + ($scope.administrationFee ? $scope.administrationFee : 0)
            +( $scope.agentCommission ?  $scope.agentCommission:0) + ($scope.legalFee ? $scope.legalFee:0);

    }

    $scope.calculate = function () {
        validation();
        if ($scope.warning.length > 0)
            return;
        else
            $scope.warning = null
        rpgtRate();
        $scope.exemptionWaiver1 = ($scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0)) * 0.1;
        $scope.rpgt1 = $scope.rpgtRate1 / 100 * ($scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0) - $scope.exemptionWaiver1);
        $scope.rpgt2 = $scope.rpgtRate2 / 100 * ($scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0));
        $scope.rpgt3 = $scope.rpgtRate3 / 100 * ($scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0));
        // Net gain
        $scope.netGain1 = $scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0) - $scope.rpgt1;
        $scope.netGain2 = $scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0) - $scope.rpgt2;
        $scope.netGain3 = $scope.sellingPrice - $scope.propertyPrice - ($scope.totalExpensesFee ? $scope.totalExpensesFee : 0) - $scope.rpgt3;
        $scope.calFinish = true;
    }

    function rpgtRate()
    {
        switch ($scope.holdingYear) {
            case 1:
                $scope.rpgtRate1 = 30;
                $scope.rpgtRate2 = 30;
                $scope.rpgtRate3 = 30;
                break;
            case 2:
                $scope.rpgtRate1 = 30;
                $scope.rpgtRate2 = 30;
                $scope.rpgtRate3 = 30;
                break;
            case 3:
                $scope.rpgtRate1 = 30;
                $scope.rpgtRate2 = 30;
                $scope.rpgtRate3 = 30;
                break;
            case 4:
                $scope.rpgtRate1 = 20;
                $scope.rpgtRate2 = 20;
                $scope.rpgtRate3 = 30;
                break;
            case 5:
                $scope.rpgtRate1 = 15;
                $scope.rpgtRate2 = 15;
                $scope.rpgtRate3 = 30;
                break;

            default:
                $scope.rpgtRate1 = 0;
                $scope.rpgtRate2 = 5;
                $scope.rpgtRate3 = 5;
        }
    }
    $scope.close = function () {

        $scope.warning = null;
        $scope.error = null;
        $scope.info = null;
    }

    function validation()
    {
        $scope.warning = [];
        if (!$scope.sellingPrice)
            $scope.warning.push({ msg: "Selling price must not be empty!" })
        if (!$scope.propertyPrice)
            $scope.warning.push({ msg: "Purchase price must not be empty!" })
        if (!$scope.holdingYear)
            $scope.warning.push({ msg: "Holding year must not be empty!" })

    }

})
myApp.controller("lawyerfeeController", function ($scope, $http, $modal, $routeParams, authService, $location, $window) {
    document.title = "Penang Realty 世界地產 Legal Fee Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 Legal Fee Calculator', 'description': 'Free online lawyer fee calculator. Try it now.' });
    $scope.calculate = function () {
        validation();
        if ($scope.warning.length > 0)
            return;
        else
            $scope.warning = null;

        $scope.snpLegalfee = 0;
        if ($scope.propertyPrice <= 150000){
            $scope.snpLegalfee = Math.max(0.01 * $scope.propertyPrice,300);
        }
        else if ($scope.propertyPrice <= 1000000){
            $scope.snpLegalfee = 150000 * 0.01 + ($scope.propertyPrice - 150000) * 0.007;
        }
        else if($scope.propertyPrice <= 3000000){
            $scope.snpLegalfee = 150000 * 0.01 + (850000) * 0.007 + (3000000 - $scope.propertyPrice) * 0.006;
        }
        else if ($scope.propertyPrice <= 5000000){
            $scope.snpLegalfee = 150000 * 0.01 + (850000) * 0.007 + (2000000) * 0.006 + (5000000 - $scope.propertyPrice) * 0.005;
        }
        else if ($scope.propertyPrice <= 7500000){
            $scope.snpLegalfee = 150000 * 0.01 + (850000) * 0.007 + (2000000) * 0.006 + (2000000) * 0.005 + (7500000 - $scope.propertyPrice) * 0.004;
        }
        else {
            $scope.snpLegalfee = 150000 * 0.01 + (850000) * 0.007 + (2000000) * 0.006 + (2000000) * 0.005 + (2500000) * 0.04 + ($scope.propertyPrice - 7500000) * 0.004;
        }
      
        $scope.snpStampDuty = 0;
        if ($scope.propertyPrice < 100000) {
            $scope.snpStampDuty = $scope.propertyPrice * 0.01;
        }
        else if ($scope.propertyPrice < 500000) {
            $scope.snpStampDuty = 100000 * 0.01 + (500000 - $scope.propertyPrice) * 0.02;
        }
        else {
            $scope.snpStampDuty = 100000 * 0.01 + (400000) * 0.02 + ($scope.propertyPrice -500000)*0.03;
        }
        $scope.snpTotal = $scope.snpLegalfee + $scope.snpStampDuty;

        $scope.loanLegal = 0;
        if ($scope.propertyPrice <= 150000) {
            $scope.loanLegal = Math.max(0.01 * $scope.propertyPrice, 300);
        }
        else if ($scope.propertyPrice <= 1000000) {
            $scope.loanLegal = 150000 * 0.01 + ($scope.propertyPrice - 150000) * 0.007;
        }
        else if ($scope.propertyPrice <= 3000000) {
            $scope.loanLegal = 150000 * 0.01 + (850000) * 0.007 + (3000000 - $scope.propertyPrice) * 0.006;
        }
        else if ($scope.propertyPrice <= 5000000) {
            $scope.loanLegal = 150000 * 0.01 + (850000) * 0.007 + (2000000) * 0.006 + (5000000 - $scope.propertyPrice) * 0.005;
        }
        else if ($scope.propertyPrice <= 7500000) {
            $scope.loanLegal = 150000 * 0.01 + (850000) * 0.007 + (2000000) * 0.006 + (2000000) * 0.005 + (7500000 - $scope.propertyPrice) * 0.004;
        }
        else {
            $scope.loanLegal = 150000 * 0.01 + (850000) * 0.007 + (2000000) * 0.006 + (2000000) * 0.005 + (2500000) * 0.04 + ($scope.propertyPrice - 7500000) * 0.004;
        }
        $scope.loanStampDuty = $scope.propertyPrice * 0.005;
        $scope.loanTotal = $scope.loanLegal + $scope.loanStampDuty;

        $scope.total = $scope.loanTotal + $scope.snpTotal;



        
    }

    function validation() {
        $scope.warning = [];       
        if (!$scope.propertyPrice)
            $scope.warning.push({ msg: "Purchase price must not be empty!" })
       

    }
})
myApp.controller("stampDutyController", function ($scope, $http, $modal, $routeParams,authService, $location, $window) {
    document.title = "Penang Realty 世界地產 Stamp Duty Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Stamp Duty Calculator', 'description': 'Free online stamp duty calculator. Try it now.' });

})
myApp.controller("propertySearchController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window, $rootScope) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent', 'description': 'Free search for properties you want.' });

    $scope.data.searchData = [];
    $scope.internaluser = false;
    
    if ($scope.authentication.userType !== "Valid User" && $scope.authentication.userType !== "") $scope.internaluser = true;

    console.log($scope.authentication.userType);

    function pageInit() {
        $http.get('api/Property/GetState')
             .success(function (data) {
                 $scope.states = data;
                 $scope.search();
            })
        
    }

    $scope.changeState = function () {
        if ($scope.property.StateId) {
            $http.get('api/Property/GetLocation/' + $scope.property.StateId)
           .success(function (data) {

               $scope.locations = data;
           }
           )
        }
    }

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 25,           // count per page
        filter: {
            //Project: ''       // initial filter
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {
            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));         
        }
    })

    $scope.search = function () {
        $scope.loader.loading = true;
        validateSearch();

        console.log("Scope=");
        console.log($scope);
        console.log($scope.tableParams);
        if ($scope.tableParams !== undefined) $scope.tableParams.reload();

        if ($scope.property.transact == "S") url = 'api/PropertySearch/GetSaleProperty';
        else url = 'api/PropertySearch/GetRentProperty';
        //console.log("$scope.property : ");
        //location.hash = "#notification";
        //var element_to_scroll_to = document.getElementById('notification');
        //element_to_scroll_to.scrollIntoView();

        $http.post(url, $scope.property)
             .success(function (result) {
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 window.prerenderReady = true;
                               
             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 window.prerenderReady = true;

             }
         )        
    }

    $scope.$watch('data.searchData', function (newValue, oldValue) {
           if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.go = function (key, value) {
        console.log($scope.property.transact);
        value['transact'] = $scope.property.transact;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }

    $scope.clearEntry = function () {
        $scope.property.StateName = "";
        $scope.property.Type = "";       
        $scope.property.StateId = "";
        $scope.property.transact = "";
        $scope.property.location = "";
        $scope.property.project = "";
        $scope.property.priceMin = 0;
        $scope.property.priceMax = 99999999;
        $scope.data.searchData = [];
    }

    validateSearch = function ()
    {

        if (typeof ($scope.property["priceMax"]) !== "undefined")
            if ($scope.property.priceMax == "null")
                $scope.property.priceMax = null;
         
        $scope.property.saleType = $scope.property.transact + $scope.property.Type;
    }
    pageInit();

   
})



myApp.controller("propertyDirectoryController", function ($scope, $http, $modal, $routeParams, authService, ngTableParams, $filter, $location, $window, $rootScope) {
    document.title = "Penang Realty 世界地產 Our Marketing Project";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Our Marketing Project', 'description': 'Enjoy great discount. Check our marketing projects now.' });
    function pageInit() {
        $scope.loader = { loading: true };
        var url = 'api/PropertyDirectory/GetPropertyDirectory';
        $http.get(url).success(function (data) {
            console.log(data);
            $scope.data.Property = data;

            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 25,           // count per page
                filter: {
                    ProjectName: ''       // initial filter
                }

            }, {
                total: $scope.data.Property.length, // length of data
                getData: function ($defer, params) {

                    var orderedProperty = params.filter() ? $filter('filter')($scope.data.Property, params.filter()) : $scope.data.Property;
                    // use build-in angular filter
                    orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
                    params.total(orderedProperty.length); // set total for recalc pagination
                    $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    $scope.loader = { loading: false };
                }
            })


        })
        
    }
    $scope.go = function (key, value) {
        //property.ProjectId,property
        console.log(key);
        console.log(value);
        value['Project'] = $scope.property;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }
    pageInit();



})

myApp.controller("PropertyDirectoryDetailController", function ($scope, $http, $modal, modalService, $routeParams, $location) {
    $scope.share = {};

    function pageInit() {
        var url = 'api/PropertyDirectory/GetPropertyDirectory/' + $routeParams.id;
        $http.get(url).success(function (data) {

            $scope.slides = data.pictureList;
            //dataInherit = data.project;
            //var dataInherit = sessionStorage.getItem($routeParams.id);
            //jsonObj = JSON.parse(dataInherit);
            $scope.Project = data.project;

            if (!$scope.slides) {
                $scope.slides = [];
                $scope.slides.push({ pictureURL: 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png' });
            }

            $scope.share.url = 'http://www.penangrealty.my/PropertyDirectoryDetail/' + $routeParams.id.toString();
            $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
            $scope.share.title = "[" + $scope.Project.ProjectName + "]" 
            $scope.share.description =  $scope.Project.ProjectLocation
                + '\n' + $scope.Project.ProjectDetails;
            console.log($scope.share.title);
            document.title = "Penang Realty 世界地產 " + $scope.Project.ProjectName;
            console.log(document.title);
            $scope.$emit('newPageLoaded', { 'title': $scope.share.title, 'description': $scope.share.description });

        })

    }
    pageInit();
});
myApp.controller("propertyNewController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter,$rootScope) {
    document.title = "Penang Realty 世界地產 New Marketing Project";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Property Directory', 'description': 'Check out our our property directory in Penang.' });
    function pageInit() {
            $scope.loader = { loading: true };
            var url = 'api/PropertyNew/GetPropertyNew';
            $http.get(url).success(function (data) {
                console.log(data);
                $scope.data.Property = data;

                $scope.tableParams = new ngTableParams({
                    page: 1,            // show first page
                    count: 25,           // count per page
                    filter: {
                        ProjectName: ''       // initial filter
                    }

                }, {
                    total: $scope.data.Property.length, // length of data
                    getData: function ($defer, params) {

                        var orderedProperty = params.filter() ? $filter('filter')($scope.data.Property, params.filter()) : $scope.data.Property;
                        // use build-in angular filter
                        orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
                        params.total(orderedProperty.length); // set total for recalc pagination
                        $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        $scope.loader = { loading: false };
                    }
                })


            })

        }
        pageInit();

})

myApp.controller("eventsController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {
    function pageInit() {
        document.title = "Penang Realty 世界地產 EVENTS";
        $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 EVENTS', 'description': 'Join our event to obtain first hand info.' });
        $scope.loader = { loading: true };
        var url = 'api/Events/GetEvents';
        $http.get(url).success(function (data) {
            $scope.data.Events = data;

            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 5,           // count per page
                filter: {
                    Name: ''       // initial filter
                }

            }, {
                total: $scope.data.Events.length, // length of data
                getData: function ($defer, params) {

                    var orderedEvents = params.filter() ? $filter('filter')($scope.data.Events, params.filter()) : $scope.data.Events;
                    // use build-in angular filter
                    orderedEvents = params.sorting() ?  $filter('orderBy')(orderedEvents, params.orderBy()) : orderedEvents;
                    params.total(orderedEvents.length); // set total for recalc pagination
                    $defer.resolve(orderedEvents.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    $scope.loader = { loading: false };
                }
            })


        })

    }
    pageInit();



})
myApp.controller("eventDetailController", function ($scope, $http, $modal, modalService, $routeParams, $location) {
    $scope.share = {};
    function pageInit() {
        var url = 'api/Events/GetEvent/' + $routeParams.id;
        $http.get(url).success(function (data) {
            $scope.Event = data.Events;
            $scope.Event.StartDateTime = new Date($scope.Event.StartDateTime);
            $scope.Event.EndDateTime = new Date($scope.Event.EndDateTime);
            $scope.slides = data.pictureList;


            $scope.share.url = 'http://www.penangrealty.my/EventDetail/' + $routeParams.id.toString();
            $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
            $scope.share.description = "[" + $scope.Event.Name + '] ' + $scope.Event.Venue + "\n" + $scope.Event.StartDateTime + " - " + $scope.Event.EndDateTime
+ '\n' + $scope.Event.Details + '\n' + window.location.href + '\n';

            document.title = "Penang Realty 世界地產 " + $scope.Event.Name;
            $scope.$emit('newPageLoaded', { 'title': $scope.Event.Name, 'description': $scope.share.description });
        })

    }
    pageInit();
});
myApp.controller("UsefulInfoController", function ($scope, $http, $modal, modalService, $routeParams,ngTableParams,$filter, $location) {
    document.title = "Penang Realty 世界地產 Useful Info";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Useful Info', 'description': 'First hand property info. Updated instantly.' });
    function pageInit() {
            $scope.loader = { loading: true };
            var url = 'api/UsefulInfo/GetUsefulInfo';
            $http.get(url).success(function (data) {
                $scope.data.Info = data;
                console.log(data);
                $scope.tableParams = new ngTableParams({
                    page: 1,            // show first page
                    count: 5,           // count per page
                    filter: {
                        Title: ''       // initial filter
                    }

                }, {
                    total: $scope.data.Info.length, // length of data
                    getData: function ($defer, params) {

                        var orderedInfo= params.filter() ? $filter('filter')($scope.data.Info, params.filter()) : $scope.data.Info;
                        // use build-in angular filter
                        orderedInfo = params.sorting() ? $filter('orderBy')(orderedInfo, params.orderBy()) : orderedInfo;
                        params.total(orderedInfo.length); // set total for recalc pagination
                        $defer.resolve(orderedInfo.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        $scope.loader = { loading: false };
                    }
                })


            })

        }
       pageInit();
})


myApp.controller("UsefulInfoDetailController", function ($scope, $http, $modal, modalService, $routeParams, $location) {
    $scope.share = {};
    function pageInit() {
        var url = 'api/UsefulInfo/GetUsefulInfo/' + $routeParams.id;
        $http.get(url).success(function (data) {
            $scope.UsefulInfo = data.UsefulInfo;
          
            $scope.slides = data.pictureList;

            $scope.share.url = 'http://www.penangrealty.my/UsefulInfoDetail/' + $routeParams.id.toString();
            $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
            $scope.share.title = $scope.UsefulInfo.Title 
            $scope.share.description =  "[" + $scope.UsefulInfo.Source + "] " + $scope.UsefulInfo.description 
                + '\n' + $scope.UsefulInfo.Details;
            document.title = "Penang Realty 世界地產 " + $scope.share.Title;
            $scope.$emit('newPageLoaded', { 'title': $scope.share.title, 'description': $scope.share.description });
        })

    }
    pageInit();
});
myApp.controller("propertyNewController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter,$rootScope) {
    document.title = "Penang Realty 世界地產 New Marketing Project";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Property Directory', 'description': 'Check out our our property directory in Penang.' });
    function pageInit() {
            $scope.loader = { loading: true };
            var url = 'api/PropertyNew/GetPropertyNew';
            $http.get(url).success(function (data) {
                console.log(data);
                $scope.data.Property = data;

                $scope.tableParams = new ngTableParams({
                    page: 1,            // show first page
                    count: 25,           // count per page
                    filter: {
                        ProjectName: ''       // initial filter
                    }

                }, {
                    total: $scope.data.Property.length, // length of data
                    getData: function ($defer, params) {

                        var orderedProperty = params.filter() ? $filter('filter')($scope.data.Property, params.filter()) : $scope.data.Property;
                        // use build-in angular filter
                        orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
                        params.total(orderedProperty.length); // set total for recalc pagination
                        $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        $scope.loader = { loading: false };
                    }
                })


            })

        }
        pageInit();

})

myApp.controller("PropertyNewDetailController", function ($scope, $http, $modal, modalService, $routeParams, $location) {
    
    $scope.share = {};
    function pageInit() {
        var url = 'api/PropertyNew/GetPropertyNew/' + $routeParams.id;
        $http.get(url).success(function (data) {
            $scope.Project = data.PropertyNew;
            $scope.slides = data.pictureList;
            $scope.share.url = 'http://www.penangrealty.my/PropertyNewDetail/' + $routeParams.id.toString();
            $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
            $scope.share.title = '[New Property] ' + $scope.Project.ProjectName + " " + $scope.Project.ProjectLocation
            document.title = "Penang Realty 世界地產 " + $scope.share.Title;
            $scope.share.description = "Price : " + $scope.Project.ProjectPrice.toLocaleString() + ". " + $scope.Project.ProjectDetails
            $scope.$emit('newPageLoaded', { 'title': $scope.share.title, 'description': $scope.share.description });
        })

    }
    pageInit();
});
myApp.controller("registerController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter, authService, $timeout,$location) {
    document.title = "Penang Realty 世界地產 Member Registration";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Member Registration', 'description': 'Register to become our member to enjoy extra benefits.' });
    $scope.close = function () {
        $scope.warning = null;
        $scope.error = null;
        $scope.info = null;
    }
    var startTimer = function () {
        $timeout(function () {
            $location.path('/Login')
        }, 2000);

    }

    function validateEmail(email) {
        var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        return re.test(email);
    }

    $scope.save = function () {
        if (!validation()) return;
        authService.saveRegistration($scope.data).then(function (response) {
            if (response.data == "Success") {
                $scope.info = "Registration successful! You will be redirected to login page in 2 secs";
                console.log(response);
                startTimer();
            }
            else
                $scope.info = response.data;
        }),
        function (response) {

            console.log(response);
        };

        
       // $http.post('api/User/save', $scope.data )
       //.success(function (result) {
       //    var output = result;
       //    if (output == "Success") {

       //    }

       //})

    }

    

    function validation()
    {
        $scope.warning = [];
        if (!$scope.data.Name)
            $scope.warning.push({ msg: "Name cannot be empty!" });
        if (!$scope.data.Email)
            $scope.warning.push({ msg: "Email must not be empty!" });
        if (!$scope.data.Handphone)
            $scope.warning.push({ msg: "Handphone must not be empty!" });
        if (!$scope.data.Password)
            $scope.warning.push({ msg: "Password must not be empty!" });
        if ($scope.data.Password !=$scope.data.ConfirmedPassword )
            $scope.warning.push({ msg: "Password and confirmed passwored must be the same!" });
        if (!validateEmail($scope.data.Email))
            $scope.warning.push({ msg: "Invalid email account!" });
        if ($scope.warning.length > 0)
            return false;
        else {
            $scope.warning = null;
            return true;
        }
    }

})
myApp.controller("propertyController", function ($scope, $http, $modal, modalService, $routeParams, $location, $filter,$compile, NgMap) {
    
    $scope.share = {};
    NgMap.getMap().then(function (map) {
        $scope.map = map;
    });

   
    $scope.showProperty = function (evt, data) {
        $scope.store = data;
        console.log(data);
        if ($routeParams.listType.substring(0, 1) == 'S') {           
            $scope.store.displayPrice =  "Sale Price : RM" + data.SalePrice.toLocaleString();
        } else {
            $scope.store.displayPrice =  "Rental Price : RM" + data.RentPrice.toLocaleString();
        }
        $scope.map.showInfoWindow('foo', this);
    };

    $scope.showInfoWindow = function (evt, storeId) {
        //$scope.store = $scope.stores[storeId];
        console.log("google showInfoWindow");
        console.log(this);
        console.log(storeId);
        console.log(evt);
        $scope.map.showInfoWindow('foo', this);
    };
    $scope.mouseover = function () {
        console.log('mouseover');
    };
    function pageInit() {
        

        if ($routeParams.id) {
            // get from session storage
            // if there is data in session
            var data = sessionStorage.getItem($routeParams.id);
            

            // if no data in session, get from the server
            jsonObj = JSON.parse(data);
            $scope.property = jsonObj;
           // console.log($scope.property);
            var url = 'api/Property/GetPropertyDetailByListType/' + $routeParams.id + '/' + $routeParams.listType;
            $http.get(url).success(function (data) {
                $scope.property = data.propertyDetail;

                console.log("this is all the data ", $scope.property);
             
                $scope.property.listType = $routeParams.listType;

                var transactStr;
                if ($routeParams.listType.substring(0, 1) == 'S') {
                    $scope.property.transact = 'S';                    
                    $scope.nearByList = data.nearByListSale;
                    var toBeFilter = $filter('filter')($scope.nearByList, { propertyid: $routeParams.id });
                    var index = $scope.nearByList.indexOf(toBeFilter[0]);
                    $scope.nearByList.splice(index, 1);
                    transactStr = " FOR SALE" + "\n" + "Sale Price : RM" + $scope.property.SalePrice.toLocaleString();
                } else {
                    $scope.property.transact = 'R';
                    $scope.nearByList = data.nearByListRent;
                    transactStr = " FOR RENT" + "\n" + "Rental Price : RM" + $scope.property.RentPrice.toLocaleString();
                }
               // $scope.property.ListType = $scope.property.ListType.toString();
                $scope.slides = data.pictureList;
                if (!$scope.slides) {
                    $scope.slides = [];
                    $scope.slides.push({ pictureURL: 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png' });
                }
               // console.log($scope.property.StaffPicURL);
               // $scope.slides.push({ pictureURL: $scope.property.StaffPicURL });

                $scope.share.url = 'http://www.penangrealty.my/Property/' + $routeParams.id.toString() + '/' + $routeParams.listType.toString();
                $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
                $scope.share.title = $scope.property.LongHeading;
                $scope.share.description = "[" + $scope.property.location + '] ' 
                    + transactStr + '\n' //+ window.location.href + '\n'
                    + "Contact: " + $scope.property.mobile + " (" + $scope.property.agentname + ")";

                document.title = "Penang Realty 世界地產 " + $scope.share.title;

                $scope.$emit('newPageLoaded', { 'title': $scope.share.title, 'description': $scope.share.description });

                $scope.loader = { loading: false };
            }).error(function(data){
                console.log(data);
                $scope.loader = { loading: false };
            })
        }
    }

    pageInit();

});
myApp.controller("auctionController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter,$rootScope) {
    document.title = "Penang Realty AUCTION 世界地產 拍卖";
    function pageInit() {
        $scope.loader = { loading: true };
        var url = 'api/Auction/GetAuction';
        //modified by yuggo hor 
        $scope.data.searchData = [];
        $http.get('api/Property/GetState')
       .success(function (data) {
           $scope.states = data;
           $scope.search();
       })
        //end of modification 
        $http.get(url).success(function (data) {            
            $scope.data.Auctions = data;
            //console.log($scope.data.Auctions);

            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 25,           // count per page
                filter: {
                    Type: ''       // initial filter
                },
                sorting: {
                       Price: 'asc'     // initial sorting
                }

            }, {
                total: $scope.data.Auctions.length, // length of data                
                getData: function ($defer, params) {

                    var orderedAuctions = params.filter() ? $filter('filter')($scope.data.Auctions, params.filter()) : $scope.data.Auctions;
                    // use build-in angular filter
                    orderedAuctions = params.sorting() ?  $filter('orderBy')(orderedAuctions, params.orderBy()) : orderedAuctions;
                    params.total(orderedAuctions.length); // set total for recalc pagination
                    $defer.resolve(orderedAuctions.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    $scope.loader = { loading: false };

                }
            })
        })
        //modified by yuggohor
        
        $scope.changeState = function () {
            if ($scope.property.StateId) {
                $http.get('api/Property/GetLocation/' + $scope.property.StateId)
               .success(function (data) {

                   $scope.locations = data;
               }
               )
            }
        }
        $scope.search = function () {
            $scope.loader.loading = true;
            validateSearch();

            console.log("Scope=");
            console.log($scope);
            console.log($scope.tableParams);
            if ($scope.tableParams !== undefined) $scope.tableParams.reload();

            if ($scope.property.transact == "S") url = 'api/PropertySearch/GetSaleProperty';
            else url = 'api/PropertySearch/GetRentProperty';
            //console.log("$scope.property : ");
            //location.hash = "#notification";
            //var element_to_scroll_to = document.getElementById('notification');
            //element_to_scroll_to.scrollIntoView();

            $http.post(url, $scope.property)
                 .success(function (result) {
                     console.log(result);
                     $scope.loader.loading = false;
                     $scope.data.searchData = result;
                     window.prerenderReady = true;

                 })
                 .error(function (result) {
                     console.log("Error");
                     console.log(result);
                     $scope.loader.loading = false;
                     window.prerenderReady = true;

                 }
             )
        }
        $scope.$watch('data.searchData', function (newValue, oldValue) {
            if ($scope.tableParams) $scope.tableParams.reload();
        });

        $scope.go = function (key, value) {
            console.log($scope.property.transact);
            value['transact'] = $scope.property.transact;
            var jsonObj = JSON.stringify(value);
            sessionStorage.setItem(key, jsonObj);
        }

        $scope.clearEntry = function () {
            $scope.property.Type = "";
            $scope.property.StateId = "";
            $scope.property.transact = "";
            $scope.property.location = "";
            $scope.property.project = "";
            $scope.property.priceMin = 0;
            $scope.property.priceMax = 99999999;
            $scope.data.searchData = [];
        }

        validateSearch = function () {

            if (typeof ($scope.property["priceMax"]) !== "undefined")
                if ($scope.property.priceMax == "null")
                    $scope.property.priceMax = null;

            $scope.property.saleType = $scope.property.transact + $scope.property.Type;
        }
        //end of modification 
    }

    $scope.$emit('newPageLoaded', { 'title': 'Properties Auction in Penang', 'description': 'Buy below market price! House/Factory/Land/Condo/Shop' });

    pageInit();


})
myApp.controller("auctionDetailController", function ($scope, $http, $modal, modalService, $routeParams, $location) {

    // Address, Type, Price, Land/BuildUp Area, AuctionDate, Sale AgentName, Contact, Photo
    $scope.share = {};
   function pageInit() {
       var url = 'api/Auction/GetAuction/' + $routeParams.id;
       $http.get(url).success(function (data) {
           console.log(data.Auction);
           $scope.Auction = data.Auction;
           $scope.Auction.StartDateTime = new Date($scope.Auction.StartDateTime);
           $scope.Auction.EndDateTime = new Date($scope.Auction.EndDateTime);
           $scope.slides = data.pictureList;
           //$scope.slides.push({ pictureURL: $scope.Auction.StaffPicURL });
           if (!$scope.slides) {
               $scope.slides = [];
               $scope.slides.push({ pictureURL: 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png' });
           }

           $scope.share.url = 'http://www.penangrealty.my/AuctionDetail/' + $routeParams.id.toString();
            $scope.share.pictureUrl = $scope.slides ? $scope.slides[0].pictureURL : 'http://www.penangrealty.my/images/penang realty,Apartment,house,condominium,terrace house,semi d,detached,bungalow,high end luxury properties,landed properties,gated guarded house.png';
            $scope.share.title = '[拍卖 AUCTION] ' + $scope.Auction.Address
            $scope.share.description = "Price : " + $scope.Auction.Price.toLocaleString()
+ ', Land Area : ' + $scope.Auction.LandArea
+ ', Date : ' + $scope.Auction.AuctionDate
//+ " Contact: " + $scope.property.mobile + " (" + $scope.property.agentname + ")";
            document.title = "Penang Realty AUCTION 世界地產" + $scope.share.title;
            $scope.$emit('newPageLoaded', { 'title': $scope.share.title, 'description': $scope.share.description });
        })

    }
    pageInit();
   //console.log("AuctionDetail controller loaded");
});
myApp.controller("recentTransactionController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window,$rootScope) {
    document.title = "Penang Realty 世界地產 Property Transacted History";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Property Transacted History', 'description': 'Free search for real transaction histories in Penang.' });
    $scope.data.searchData = [];


    //$scope.warning = "";

    //$scope.error = "";

    //$scope.info = "";

    function pageInit() {
        $http.get('api/RecentTransaction/GetDistrict')
             .success(function (data) {         
                 console.log(data);
                 $scope.districts = data;
             }
            )
    }
    $scope.propertyType = [{"sqlName":"INDUSTRI", "displayName":"INDUSTRIAL"},
                           {"sqlName":"PEMBANGUNAN", "displayName":"DEVELOPMENT"},
                           { "sqlName": "PERTANIAN", "displayName": "AGRICULTURE" },
                           { "sqlName": "PERDAGANGAN", "displayName": "COMMERCIAL" },
                           { "sqlName": "KEDIAMAN", "displayName": "RESIDENTIAL" },
                           { "sqlName": "LAIN-LAIN", "displayName": "OTHERS" }];

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 25,           // count per page
        filter: {
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {

            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));

        }
    })

    $scope.$watch('data.searchData', function (newValue, oldValue) {
        if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.search = function () {

        $scope.warning = "";
        $scope.error = "";
        $scope.info = "";

        console.log($scope.property);

        if (validateSearch() == false) return;

        $scope.loader.loading = true;
        if ($scope.tableParams !== undefined) $scope.tableParams.reload();
        
        var url;
        if ($scope.property.saleType == "S") {
            url = 'api/RecentTransaction/GetRecentSale';
        } else {
            url = 'api/RecentTransaction/GetRecentRent'
        }
        $http.post(url, $scope.property)
            .success(function (result) {
                $scope.loader.loading = false;
                $scope.data.searchData = result;
                console.log(result);
            }
        ).error(function (result) {
            $scope.loader.loading = false;
            console.log("error getting data from server...");
            $scope.error = "Error getting data from server.";

        })
    }

    $scope.clearEntry = function () {
        $scope.property.keyword = "";
        $scope.property.saleType = "";
        $scope.property.type = "";
        $scope.property.district = "";
        $scope.data.searchData = [];
    }

    validateSearch = function()
    {
        console.log("Validate Search");
        console.log($scope.property);
        var returnval = true;
        var errorval = "";

        if ($scope.property.saleType == "" || $scope.property.saleType == "Select") {
            errorval = "Transaction Type, ";
            returnval= false;
        }
        if (!$scope.property.hasOwnProperty("district")) {
            // make it non compulsory
            $scope.property.district = "";
            //errorval = errorval + "District, ";
            //returnval= false;
        }
        if (!$scope.property.hasOwnProperty("type")) {
            errorval = errorval + "Property Type, ";
            returnval = false;
        }

        if (!$scope.property.hasOwnProperty("keyword") || $scope.property.keyword == "" || typeof $scope.property.keyword === 'undefined') {
            errorval = errorval + "Keyword ";
            returnval = false;
        }
        if (returnval == false){
            $scope.error = "Ensure these items are not empty: " + errorval;
        }
        return returnval;
        // check if all input are selected.
    }

    pageInit();

   
})



myApp.controller('HeaderController', function ($scope, $location) {

    $scope.isActive = function (viewLocation) {
        return viewLocation === $location.path();
    };
});
myApp.controller('FooterController', function ($scope, $location, $http) {

    var inputString = window.location.href;
    var findme = "escaped_fragement";
    var findme2 = "ListingEntry";
    if ((inputString.indexOf(findme) > -1) || (inputString.indexOf(findme2) > -1)) {
        console.log("Don't do background get");
        $scope.url = "";
    } else {

        $scope.url = window.location.href + "?_escaped_fragment_=";
        console.log("Try background get");
        $http({
            method: 'GET',
            url: $scope.url
        }).then(function successCallback(response) {
            console.log("Background call Success");
            console.log(response);
        }, function errorCallback(response) {
            console.log("Background call Fail");
            console.log(response);
        });
    }    
    console.log($scope.url);
});
myApp.controller("BuyRentController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 BUY RENT";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 BUY RENT', 'description': 'We have variety of properties for you to choose.' });
    function pageInit() {
        $scope.loader = { loading: false };

    }
    pageInit();
    $scope.property = {

    };

    $scope.save = function () {
        $scope.loader.loading = true;


        window.scrollBy(0, -10000);
        if (!validation())
            return;

        url = 'api/BuyRent/save';
        
        $http.post(url, $scope.property)
             .success(function (result) {
                 console.log("Data return!");
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 $scope.info = "Your request has been submitted successfully. We thank you for your enquiry.";

             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.error = "Your request cannot be submitted now. Please contact our office directly for us to serve you immediately.";
             }
         )
    }


    $scope.clearEntry = function () {
        $scope.property.name = "";
        $scope.property.phone = "";
        $scope.property.phone = "";
        $scope.property.locationKeyword = "";
        $scope.property.propertyType = "Residential";
        $scope.property.submissionType = "Buy";
        $scope.property.useInvest = "";
        $scope.property.remark = "";
        $scope.property.price = 0;
        $scope.close();
    }

    $scope.close = function () {
        $scope.warning = null;
        $scope.info = null;
        $scope.error = null;
    }

    function validation() {
        $scope.warning = [];

        if (!$scope.property.locationKeyword)
            $scope.warning.push({ msg: "Location must not be empty!" });
        if (!$scope.property.price)
            $scope.warning.push({ msg: "Budget must not be empty!" });
        if (!$scope.property.name)
            $scope.warning.push({ msg: "Name must not be empty!" });
        if (!$scope.property.phone)
            $scope.warning.push({ msg: "Phone Number must not be empty!" });
        
        if ($scope.warning.length > 0)
            return false;
        else {
            $scope.warning = null;
            return true;
        }
    }
})
myApp.controller("SaleLetController", function ($scope, $http, $modal, modalService, $routeParams, $location) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 SELL LET";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 SELL LET', 'description': 'Let us help you sell or rent your property FAST!.' });
    $scope.save = function () {       
        if (!validation())
            return false;
        $scope.loader.loading = true;
        var formData = new FormData();
        //formData.append('image', image.file);
        angular.forEach($scope.data.images, function (image) {
            formData.append('image', image.resized.dataURL);
        })
       
        formData.append('property', angular.toJson($scope.property));
        $http.post('api/SaleLet/save', formData, {
            headers: { 'Content-Type': undefined },
            transformRequest: angular.identity
        }).success(function (result) {
            $scope.info = [];
            $scope.info ="Thanks for your submission. Your data is saved successfully!";
            $scope.clearEntry();
            $scope.loader.loading = false;

        });
    }

  
    $scope.clearEntry = function () {
        $scope.property.submissionType = "Sale";
        $scope.property.address = null;
        $scope.property.name = null;
        $scope.property.price = null;
        $scope.property.email = null;
        $scope.property.remark = null;
        $scope.property.phone = null;
        $scope.property.company = null;
        $scope.data.images = null;
        angular.element("input[type='file']").val(null);
       
    }

    function validateEmail(email) {
        var re = /^([\w-]+(?:\.[\w-]+)*)@((?:[\w-]+\.)*\w[\w-]{0,66})\.([a-z]{2,6}(?:\.[a-z]{2})?)$/i;
        return re.test(email);
    }

    function validation() {
        $scope.warning = [];
              
        if (!$scope.property.submissionType)
            $scope.warning.push({ msg: "Submission type is not selected!" });
        if (!$scope.property.price)
            $scope.warning.push({ msg: "Budget must not be empty!" });
        if (!$scope.property.name)
            $scope.warning.push({ msg: "Name must not be empty!" });
        if (!$scope.property.phone)
            $scope.warning.push({ msg: "Phone Number must not be empty!" });
        if (!$scope.property.address)
            $scope.warning.push({ msg: "address must not be empty!" });
        if ($scope.property.email) {
            if (!validateEmail($scope.property.email))
                $scope.warning.push({ msg: "Email format is not correct!" });
        }
        if ($scope.data.images) {
            if ($scope.data.images.length > 3)
                $scope.warning.push({ msg: "Maximum 3 images!" });
        }

        if ($scope.warning.length > 0)
            return false;
        else {
            $scope.warning = null;
            return true;
        }
    }
})
myApp.controller("ForgetPasswordController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {

    $scope.submit = function () {
        if (!validation())
            return;
        url = 'api/User/userForgetPassword';
        
        $http.post(url, $scope.data)
             .success(function (result) {               
                 $scope.loader.loading = false;
                 $scope.info = "Your request has been submitted successfully. Please check your email.";
                 $scope.data.Name = null;
                 $scope.data.Email = null;

             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.error = "Your request cannot be submitted now. Please contact our office directly for us to serve you immediately.";
             })
             
        

    }

    function validation() {
        $scope.warning = [];

        if (!$scope.data.Name)
            $scope.warning.push({ msg: "Name must not be empty!" });
        if (!$scope.data.Email)
            $scope.warning.push({ msg: "Email must not be empty!" });
       
        if ($scope.warning.length > 0)
            return false;
        else {
            $scope.warning = null;
            return true;
        }
    }

})
myApp.controller("CareerController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {
    document.title = "Penang Realty 世界地產 CAREER";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 CAREER', 'description': 'Earn more than 10K per month, Join us!' });
    function pageInit() {
        // get description
        $http.get('api/Career/GetJobPositions')
             .success(function (data) {

                 $scope.job = data;
             }
        )

        $http.get('api/Career/GetJobDescription')
            .success(function (data) {

            $scope.description = data;
            }
        )
        // get job vacancy

        $scope.loader = { loading: false };

    }
    pageInit();
    $scope.person = {

    };

    $scope.save = function () {
        $scope.loader.loading = true;


        window.scrollBy(0, -10000);
        if (!validation())
            return;

        url = 'api/Career/save';
        
        $http.post(url, $scope.person)
             .success(function (result) {
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 $scope.info = "Your request has been submitted successfully. We thank you for your application.";

             })
             .error(function (result) {
                 $scope.loader.loading = false;
                 $scope.error = "Your request cannot be submitted now. Please contact our office directly for us to liase with you immediately.";
             }
         )
    }


    $scope.clearEntry = function () {
        $scope.person.name = "";
        $scope.person.phone = "";
        $scope.person.gender = "";
        $scope.person.ic = "";
        $scope.person.address = "";
        $scope.person.position = "";
        $scope.close();
    }

    $scope.close = function () {
        $scope.warning = null;
        $scope.info = null;
        $scope.error = null;
    }

    function validation() {
        $scope.warning = [];

        if (!$scope.person.name)
            $scope.warning.push({ msg: "Name must not be empty!" });
        if (!$scope.person.phone)
            $scope.warning.push({ msg: "Phone must not be empty!" });
        if (!$scope.person.ic)
            $scope.warning.push({ msg: "IC must not be empty!" });
        
        if ($scope.warning.length > 0)
            return false;
        else {
            $scope.warning = null;
            return true;
        }
    }
})
myApp.controller("TenancyController", function ($scope, $http, $modal, modalService, $routeParams, $location, $filter,$compile, NgMap) {
    document.title = "Penang Realty 世界地產 Tenancy Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Tenancy Calculator', 'description': 'Free online tenancy calculator. Try it now.' });
    $scope.calculate = function () {
        // http://expatriateadvisory.com/guide-in-renting-a-property-in-malaysia/
        var rentalTotal = $scope.rentalPrice * 12 * $scope.tenancyPeriod;
        $scope.stampDuty = (rentalTotal - 2400) / 250 * stampDutyRate($scope.tenancyPeriod);
        if ($scope.tenancyPeriod < 4) {
            if ($scope.rentalPrice < 10000)
                $scope.tenancyCharges = $scope.rentalPrice * 0.25;
            else 
                $scope.tenancyCharges = 10000 * 0.25 +  ($scope.rentalPrice-10000) * 0.20;
         }
        else
        {
            if ($scope.rentalPrice < 10000)
                $scope.tenancyCharges = $scope.rentalPrice * 0.50;
            else
                $scope.tenancyCharges = 10000 * 0.50 + ($scope.rentalPrice - 10000) * 0.20;

        }
        $scope.total = $scope.tenancyCharges + $scope.stampDuty + ($scope.addionalCopy * 19)
    }
    function stampDutyRate(year) {
        if (year < 2)
            return 1;
        else if (year < 3)
            return 2;
        else
            return 3;

    }
})
myApp.controller("BestBuyController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window,$rootScope) {
    $scope.data.searchData = [];
    $scope.internaluser = false;
    document.title = "Penang Realty BESTBUY 世界地產 BESTBUY";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BESTBUY 世界地產 BESTBUY', 'description': 'Bestbuy properties you should not miss, come and see!' });
    if ($scope.authentication.userType !== "Valid User" && $scope.authentication.userType !== "") $scope.internaluser = true;

    console.log($scope.authentication.userType);

    function pageInit() {
        bestBuySearch();
    }



    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 25,           // count per page
        filter: {
            //Project: ''       // initial filter
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {
            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));         
        }
    })

    bestBuySearch = function () {
        $scope.loader.loading = true;

        if ($scope.tableParams !== undefined) $scope.tableParams.reload();

        url = 'api/PropertySearch/GetBestBuytProperty';

        var element_to_scroll_to = document.getElementById('notification');
        element_to_scroll_to.scrollIntoView();

        $http.post(url, $scope.property)
             .success(function (result) {
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 window.prerenderReady = true;
                               
             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 window.prerenderReady = true;
             }
         )        
    }

    $scope.$watch('data.searchData', function (newValue, oldValue) {
           if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.go = function (key, value) {
        console.log($scope.data.SaleType);
        value['transact'] = $scope.data.SaleType;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }



    pageInit();

   
})



myApp.controller('GalleryController', function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {
    document.title = "Penang Realty 世界地產 Gallery";

    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 Gallery', 'description': 'Beautiful property photos in Penang.' });
    $scope.images = [];
    pageInit();
    
    function pageInit() {
        $scope.loader = { loading: true };
        var url = 'api/Page/GetGallery';
        $http.get(url).success(function (data) {
            $scope.data.images = data;
            angular.forEach(data, function (value) {
                $scope.images.push({ thumb: value.thumnail, img: value.pictureURL, description: value.Description });
            })
            console.log( $scope.images);

            $scope.loader.loading = false;
        })
        //img.onload = function () {
        //    $scope.$apply(function () {
        //        $scope.images.width = img.width;
        //        $scope.images.height = img.height;
        //        $scope.images.path = $scope.imageurl;
        //    });
        //}
   }


    $scope.data.images = [
        { thumb: 'images/appstore.jpg', img: 'images/close.png', description: 'Image 1' },
    
    ];


})
myApp.controller("HomeController", function ($scope, $http, $modal, modalService, $sce, ngTableParams, $filter) {
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 News', 'description': 'First hand property news. Updated instantly.' });
    $scope.thisPage = {};

    
    function pageInit() {
        //document.title = "Penang Realty 世界地產 EVENTS";
        //$scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 EVENTS', 'description': 'Join our event to obtain first hand info.' });
        $scope.loader = { loading: true };
        var url = 'api/Events/GetEvents';
        $http.get(url).success(function (data) {
            $scope.data.Events = data;
            console.log(data);
/*
            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 5,           // count per page
                filter: {
                    Name: ''       // initial filter
                }

            }, {
                total: $scope.data.Events.length, // length of data
                getData: function ($defer, params) {

                    var orderedEvents = params.filter() ? $filter('filter')($scope.data.Events, params.filter()) : $scope.data.Events;
                    // use build-in angular filter
                    orderedEvents = params.sorting() ?  $filter('orderBy')(orderedEvents, params.orderBy()) : orderedEvents;
                    params.total(orderedEvents.length); // set total for recalc pagination
                    $defer.resolve(orderedEvents.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    $scope.loader = { loading: false };
                }
            })

*/
        })

    }
    

    function pageInit2() {
        $scope.thisPage.loading = true;
        var url = 'api/News/GetNews';
        $http.get(url).success(function (data) {
            $scope.thisPage.loading = false;
            $scope.data.News = data;
            console.log(data);

            /*
            $scope.tableParams = new ngTableParams({
                page: 1,            // show first page
                count: 25,           // count per page
                filter: {
                    Title: ''       // initial filter
                }

            }, {
                total: $scope.data.News.length, // length of data
                getData: function ($defer, params) {

                    var orderedNews = params.filter() ? $filter('filter')($scope.data.News, params.filter()) : $scope.data.News;
                    // use build-in angular filter
                    orderedNews = params.sorting() ?
                            $filter('orderBy')(orderedNews, params.orderBy()) : orderedNews;

                    params.total(orderedNews.length); // set total for recalc pagination
                    $defer.resolve(orderedNews.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                    $scope.loader = { loading: false };
                }
            })
            
            */
        })

    }


    pageInit();
    pageInit2();



})
myApp.controller("AgentsController", function ($scope, $http, $modal, modalService, $routeParams,ngTableParams,$filter, $location) {
    document.title = "Penang Realty 世界地產 Agents";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Agents', 'description': 'Professional property agents.' });
    function pageInit() {
            $scope.loader = { loading: true };
            var url = 'api/User/GetAgentList';
            $http.get(url).success(function (data) {
                $scope.data.Info = data;
                console.log(data);
                $scope.tableParams = new ngTableParams({
                    page: 1,            // show first page
                    count: 25,           // count per page
                    filter: {
                        username: ''       // initial filter
                    }

                }, {
                    total: $scope.data.Info.length, // length of data
                    getData: function ($defer, params) {

                        var orderedInfo= params.filter() ? $filter('filter')($scope.data.Info, params.filter()) : $scope.data.Info;
                        // use build-in angular filter
                        orderedInfo = params.sorting() ? $filter('orderBy')(orderedInfo, params.orderBy()) : orderedInfo;
                        params.total(orderedInfo.length); // set total for recalc pagination
                        $defer.resolve(orderedInfo.slice((params.page() - 1) * params.count(), params.page() * params.count()));
                        $scope.loader = { loading: false };
                    }
                })


            })

    }

    function pageInit2() {
        var load = false;
        //window.onload = function () {
        console.log("water mark script onload in agentController");
        if (!load) {
            wmark.init({
                /* config goes here */
                "position": "top-right", // default "bottom-right"
                "opacity": 50, // default 50
                "className": "watermark", // default "watermark"
                "path": "../images/qr.png"
            });
            load = true;
        }
        //}
    }

    //pageInit2();
    pageInit();


})


myApp.controller("AgentController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window) {
    $scope.data.searchData = [];
    $scope.agentname = "";
    $scope.agentname = $routeParams.id;
    document.title = "Penang Realty AGENT 世界地產 AGENT";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty AGENT 世界地產 AGENT', 'description': 'Bestbuy properties you should not miss, come and see!' });


    function pageInit() {
        agentPropertySearch();
    }



    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 25,           // count per page
        filter: {
            //Project: ''       // initial filter
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {
            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));         
        }
    })

    agentPropertySearch = function () {
        $scope.loader.loading = true;

        if ($scope.tableParams !== undefined) $scope.tableParams.reload();

        var pagelink = (String(window.location.href)).toUpperCase();

        if (pagelink.indexOf("RENT") > -1 ) {
            url = 'api/Property/Agent_Rent/' + $routeParams.id;

        } else {
            url = 'api/Property/Agent/' + $routeParams.id;

        }

        var element_to_scroll_to = document.getElementById('notification');
        element_to_scroll_to.scrollIntoView();

        $http.get(url)
             .success(function (result) {
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 console.log(result.data)
                 window.prerenderReady = true;
                               
             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 window.prerenderReady = true;
             }
         )        
    }

    $scope.$watch('data.searchData', function (newValue, oldValue) {
           if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.go = function (key, value) {
        console.log($scope.data.SaleType);
        value['transact'] = $scope.data.SaleType;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }



    pageInit();

   
})



myApp.controller("PropertiesController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent', 'description': 'Free search for properties you want.' });

    $scope.data.searchData = [];
    $scope.internaluser = false;
    
    if ($scope.authentication.userType !== "Valid User" && $scope.authentication.userType !== "") $scope.internaluser = true;

    console.log($scope.authentication.userType);

    function pageInit() {
        
        /*
        $http.get('api/Property/GetState')
             .success(function (data) {
                 linkRouteParam($routeParams);
                 $scope.states = data;
                 
                 $scope.search();
            }
            )
        */
    }
    $scope.query = function test() {
        
        linkRouteParam($routeParams);
        $scope.search();
    }

    function linkRouteParam(param) {
        //$scope.property.saleType = $scope.property.transact + $scope.property.Type;

        var p1 = String(param.id);
        $scope.Transact = p1;

        var p2 = String(param.id2);
        charTransact = p1.substr(0, 1);
        charType = p2.substr(0, 1);
        $scope.Type = p2;

        if (charTransact.toUpperCase() == 'R') {
            $scope.property.transact = 'R'
        } else {
            $scope.property.transact = 'S'
        }

        // TransactionType
        if (charType.toUpperCase() == 'C') {
            $scope.property.Type = 'C'
        }
        else if (charType.toUpperCase() == 'I') {
            $scope.property.Type = 'I'
        }
        else if (charType.toUpperCase() == 'L') {
            $scope.property.Type = 'L'
        }
        else {
            $scope.property.Type = 'R'
        }

    }

    $scope.changeState = function () {
        if ($scope.property.StateId) {
            $http.get('api/Property/GetLocation/' + $scope.property.StateId)
           .success(function (data) {

               $scope.locations = data;
           }
           )
        }
    }

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 50,           // count per page
        filter: {
            //Project: ''       // initial filter
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {
            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));         
        }
    })

    $scope.search = function () {
        $scope.loader.loading = true;
        validateSearch();

        if ($scope.tableParams !== undefined) $scope.tableParams.reload();

        if ($scope.property.transact == "S") url = 'api/PropertySearch/GetSaleProperty';
        else url = 'api/PropertySearch/GetRentProperty';
        //console.log("$scope.property : ");
        //location.hash = "#notification";
        var element_to_scroll_to = document.getElementById('notification');
        element_to_scroll_to.scrollIntoView();

        $http.post(url, $scope.property)
             .success(function (result) {
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 window.prerenderReady = true;
                               
             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 window.prerenderReady = true;

             }
         )        
    }

    $scope.$watch('data.searchData', function (newValue, oldValue) {
           if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.go = function (key, value) {
        console.log($scope.property.transact);
        value['transact'] = $scope.property.transact;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }

    $scope.clearEntry = function () {
        $scope.property.Type = "";
        $scope.property.StateId = "";
        $scope.property.transact = "";
        $scope.property.location = "";
        $scope.property.project = "";
        $scope.property.priceMin = 0;
        $scope.property.priceMax = 99999999;
        $scope.data.searchData = [];
    }

    validateSearch = function ()
    {

        if (typeof ($scope.property["priceMax"]) !== "undefined")
            if ($scope.property.priceMax == "null")
                $scope.property.priceMax = null;
         
        $scope.property.saleType = $scope.property.transact + $scope.property.Type;
    }
    pageInit();

   
})



myApp.controller("NewListingController", function ($scope, $http, $modal, ngTableParams, $routeParams, $filter, authService, $location, $window) {
    document.title = "Penang Realty BUY OR RENT WITH US 世界地產 New Listing";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty BUY OR RENT WITH US 世界地產 Property Sale/Rent', 'description': 'Free search for properties you want.' });

    $scope.data.searchData = [];

    console.log($scope.authentication.userType);

    function pageInit() {        

    }

    $scope.query = function test() {
        
        linkRouteParam($routeParams);
        $scope.search();
    }

    function linkRouteParam(param) {

        var p1 = String(param.id);
        $scope.Transact = p1;
        charTransact = p1.substr(0, 1);


        if (charTransact.toUpperCase() == 'R') {
            $scope.property.transact = 'R'
        } else {
            $scope.property.transact = 'S'
        }
    }

    $scope.tableParams = new ngTableParams({
        page: 1,            // show first page
        count: 50,           // count per page
        filter: {
            //Project: ''       // initial filter
        }

    }, {
        total: $scope.data.searchData.length, // length of data
        getData: function ($defer, params) {
            var orderedProperty = params.filter() ? $filter('filter')($scope.data.searchData, params.filter()) : $scope.data.searchData;
            // use build-in angular filter
            orderedProperty = params.sorting() ? $filter('orderBy')(orderedProperty, params.orderBy()) : orderedProperty;
            params.total(orderedProperty.length); // set total for recalc pagination
            $defer.resolve(orderedProperty.slice((params.page() - 1) * params.count(), params.page() * params.count()));         
        }
    })

    $scope.search = function () {
        $scope.loader.loading = true;

        if ($scope.tableParams !== undefined) $scope.tableParams.reload();

        if ($scope.property.transact == "S") url = 'api/PropertySearch/GetAllNewSaleProperty';
        else url = 'api/PropertySearch/GetAllNewRentProperty';
        //console.log("$scope.property : ");
        //location.hash = "#notification";
        var element_to_scroll_to = document.getElementById('notification');
        element_to_scroll_to.scrollIntoView();

        $http.post(url, $scope.property)
             .success(function (result) {
                 console.log(result);
                 $scope.loader.loading = false;
                 $scope.data.searchData = result;
                 window.prerenderReady = true;
                               
             })
             .error(function (result) {
                 console.log("Error");
                 console.log(result);
                 $scope.loader.loading = false;
                 window.prerenderReady = true;

             }
         )        
    }

    $scope.$watch('data.searchData', function (newValue, oldValue) {
           if ($scope.tableParams) $scope.tableParams.reload();
    });

    $scope.go = function (key, value) {
        console.log($scope.property.transact);
        value['transact'] = $scope.property.transact;
        var jsonObj = JSON.stringify(value);
        sessionStorage.setItem(key, jsonObj);
    }

    $scope.clearEntry = function () {
        $scope.property.transact = "";
        $scope.data.searchData = [];
    }


    pageInit();

   
})



myApp.controller("CalcLoanCheckerController", function ($scope, $http, $modal, modalService, $routeParams, $location, $filter,$compile, NgMap) {
    document.title = "Penang Realty 世界地產 Loan Checker Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Loan Checker Calculator', 'description': 'Free loan checker calculator. Try it now.' });

})
myApp.controller("CalcRoiController", function ($scope, $http, $modal, modalService, $routeParams, $location, $filter,$compile, NgMap) {
    document.title = "Penang Realty 世界地產 ROI Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 ROI Calculator', 'description': 'Free online ROI calculator. Try it now.' });
    $scope.calculate = function () {
        // http://expatriateadvisory.com/guide-in-renting-a-property-in-malaysia/
        var rentalTotal = $scope.rentalPrice * 12 * $scope.tenancyPeriod;
        $scope.stampDuty = (rentalTotal - 2400) / 250 * stampDutyRate($scope.tenancyPeriod);
        if ($scope.tenancyPeriod < 4) {
            if ($scope.rentalPrice < 10000)
                $scope.tenancyCharges = $scope.rentalPrice * 0.25;
            else 
                $scope.tenancyCharges = 10000 * 0.25 +  ($scope.rentalPrice-10000) * 0.20;
         }
        else
        {
            if ($scope.rentalPrice < 10000)
                $scope.tenancyCharges = $scope.rentalPrice * 0.50;
            else
                $scope.tenancyCharges = 10000 * 0.50 + ($scope.rentalPrice - 10000) * 0.20;

        }
        $scope.total = $scope.tenancyCharges + $scope.stampDuty + ($scope.addionalCopy * 19)
    }
    function stampDutyRate(year) {
        if (year < 2)
            return 1;
        else if (year < 3)
            return 2;
        else
            return 3;

    }
})
myApp.controller("CalcConvertController", function ($scope, $http, $modal, modalService, $routeParams, $location, $filter,$compile, NgMap) {
    document.title = "Penang Realty 世界地產 Tenancy Calculator";
    $scope.$emit('newPageLoaded', { 'title': 'Penang Realty 世界地產 Conversion Calculator', 'description': 'Free online Conversion calculator. Try it now.' });
    
    $scope.selectedItem = {};
    $scope.convertList = [{
        'id': 1,
        'base': 'Hectare',
        'convertUnit': 'Acres',
        'formula' : 2.471,
        'name': 'Hectare - Acres',

    }, {
        'id': 2,
        'base': 'Acre',
        'convertUnit': 'Sq Feet',
        'formula': 43560,
        'name': 'Acre - Sq Feet',
    }, {
        'id': 3,
        'base': 'Acre',
        'convertUnit': 'Meter Sq',
        'formula': 4046.86,
        'name': 'Acre - Meter Sq',
    }, {
        'id': 4,
        'base': 'Relong',
        'convertUnit': 'Sq Feet',
        'formula': 30976,
        'name': 'Relong - Sq Feet',
    }, {
        'id': 5,
        'base': 'Meter Sq',
        'convertUnit': 'Sq Feet',
        'formula': 10.7639,
        'name': 'Meter Sq - Sq Feet',
    }, {
        'id': 6,
        'base': 'Rantai',
        'convertUnit': 'Feet',
        'formula': 66,
        'name': 'Rantai - Feet',
    }, {
        'id': 7,
        'base': 'Meter',
        'convertUnit': 'Feet',
        'formula': 3.281,
        'name': 'Meter - Feet',
    }, {
        'id': 8,
        'base': 'Milimeter',
        'convertUnit': 'Feet',
        'formula': 0.003281,
        'name': 'Milimeter - Feet',
    }];

    $scope.changePage = function () {

    }

    $scope.inputKeyUp = function () {

        $scope.baseOutput = $scope.baseInput * $scope.selectedItem.formula;
    }

    $scope.outputKeyUp = function () {  

        $scope.baseInput = $scope.baseOutput / $scope.selectedItem.formula;
    }

    $scope.selectedItem = $scope.convertList[0];

    $scope.initSelect = function () {

        console.log($scope.selectedItem);
    }
})
